<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Cronjob extends CI_Controller
{	
		
	public function __construct()
	{
		parent::__construct();
		$this->load->database();		
                $this->load->model('cronjob_model');
                $this->load->model("sales_model");
                $this->load->model("user_model");
                $this->load->model("paymentlog_model");
				$this->load->model("salesphone_model");
				$this->load->model("listcustomers_model");
				//listcustomers_model
                
                $this->load->library('bookinglib');
                $this->bookinglib = new bookinglib();
        }
		
		public function testPhoneSegment(){
				$phone = $this->input->get('phone');
				$t1 = $this->cronjob_model->getPhoneC($phone);
				if($t1){
					echo $phone.' tim thay trong danh ba booking';
					echo '<pre>';print_r($t1);echo'</pre>';
				} else {
					echo $phone.' KHONG tim thay trong danh ba booking<br/>';
					$t2 = $this->sales_model->find_by(array('phone'=>$phone),'phone');
					if($t2){
						echo $phone.' tim thay trong list sale';
						echo '<pre>';print_r($t2);echo'</pre>';
					} else {
						echo $phone.' KHONG tim thay trong list SALE<br/>';
						$t3 = $this->salesphone_model->find_by(array('phone'=>$phone),'phone,status,waiting');
						if($t3){
							echo $phone.' tim thay trong list phone';
							echo '<pre>';print_r($t3);echo'</pre>';
						} else {
							echo $phone.' KHONG tim thay trong list PHONE<br/>';
						}
					}
				}
		}
		
		public function update11ve10(){//update sdt trong list phone tu 1-1 ve 1-0
				$list = $this->cronjob_model->update11ve10();
				//print_r($list);exit;
				foreach($list as $key => $value){						
							$lis            =       new stdClass();
							$lis->phone     =       $value->phone;
							$lis->status    =       1;
							$lis->waiting   =       0;
							
							$this->salesphone_model->update($lis,$value->id);
							unset($lis);
							echo $value->phone.'<br/>';
				}
		}
        
        public function getzeroe(){
            foreach($this->salesphone_model->find_by(array('status'=>1,'waiting'=>1),'id,phone') as $value){
                    $cont = $this->cronjob_model->getPhoneC($value->phone);
                    
                    if($cont){
                        $lis            =       new stdClass();
                        $lis->phone     =       $value->phone;
                        $lis->status    =       1;
                        $lis->waiting   =       0;
                        
                        $this->salesphone_model->update($lis,$value->id);
                        unset($lis);
                    }
            }
            
        }
        
        public function updatePhoneQuick(){
            $str = "";
            
            foreach(json_decode($str) as $key => $value){
                $scustomer = $this->listcustomers_model->searchCustomers(NULL,$value);
                
                if(empty($scustomer)){
                        $this->cronjob_model->updatePhoneQuick($value,0);
                } else {
                    $this->cronjob_model->updatePhoneQuick($value,1);
                }
            }
        }

        public function updatePhoneSale(){//update nhung sdt status 0 trong sale_phone , t?h?y trong danh sach sale
            
            $result = $this->salesphone_model->find_by();
//            $result = $this->cronjob_model->updatePhoneSale();
            $string = "";
            foreach($result as $key => $value){			
                    $string[$key] = $value->phone;
            }
            echo json_encode($string);
        }
        
        public function getPhoneFake(){
            $result = $this->cronjob_model->getPhoneFake();
            $number = 0;
            foreach($result as $keys => $values){
                //xu li 
                $return = $this->cronjob_model->deleteSalesPhoneTrung($values->phone);
                if($return){
                    $number++; 
                    echo 'DEL >> thanh cong sdt >>'.$values->phone.'<br/>';
                }
            }
            return $number;
        }
        
        public function autoFones(){
            $this->view_data = new stdClass();
            $this->load->view('frontend/autoFones',$this->view_data);
        }

        public function apiUpdatedbCallBusy(){
            $this->crondaily(2,0);
            
            /*$result = $this->sales_model->apiUpdateDbCallBusy();
            if($result){
               die("update status busy success ......");
            }*/
        }
        
        public function apiUpdateDb(){
             $options        = array(
                'http' => array(
                        'header' => "Content-type: application/x-www-form-urlencoded\r\n", 'method' => 'GET'
                ) 
            );
            $context                    = stream_context_create($options);
            $list                       = file_get_contents(EV_API_URL, false, $context);
            if($list == ""){
                die("API NULL");
            }
//            exit;
            $result                     = $this->bookinglib->checkPhoneValid($list);
			
            if(count($result) == 0){
                die("HET SO DIEN THOAI!");
            }
            
            $k = 0;
            foreach($result as $key => $value){
                if($value){
                    $string 		=	 new stdclass();
                    $string->phone	=	$value;	
                    $string->status	=	0;
                    $string->waiting    =	0;
                    $string->params	=	'';
                    $string->lastupdated =	date("Y-m-d H:i:s", time());
                    //test exists
                    $exists = $this->salesphone_model->find_by(array('phone'=>$value),"phone");
                    if(empty($exists)){//khong nam trong list phone
                        $_exists = $this->sales_model->find_by(array('phone'=>$value),"phone");
                        if(empty($_exists)){//neu ton tai phone trong list sale
                            $scustomer = $this->cronjob_model->getPhoneC($value);
                            if(empty($scustomer)){
                                $k++;
                                $this->salesphone_model->create($string);
								echo $value.' = 0 So moi<br/>';
                            } else {
                                $string->status	=	1;
                                $this->salesphone_model->create($string);
								echo $value.' = 1<br/>';
                            }
                        } else {
                            //update no = 1
                            $string->status	=	1;
                            $this->salesphone_model->create($string);
							echo $value.' = 1<br/>';
                        }
                    }
                    unset($string);
                }
            }

            $paramAdminLog  = array(
                'userid'            => '152',
                'lastLogin'         => date('Y-m-d :H:i:s',time()),
                'ip'                => $_SERVER['REMOTE_ADDR'],
                'logAction'         => 'He thong vua cap nhap '.$k.' SDT luc '.date("H:i:s d-m-Y", time()),
                'agent_code'        => '1'
            );
            $this->user_model->insertUserAdminLog($paramAdminLog);
            echo 'He thong vua cap nhap '.$k.' SDT luc '.date("H:i:s d-m-Y", time());
        }
		
        public function phoneRelize(){
                $_result = $this->cronjob_model->phoneRelize();
                if($_result){die("Update success!!!!");}
        }

        public function crondaily($status,$wating){
            $_result = $this->cronjob_model->selectDL($status,$wating);

            //insert
            foreach($_result as $key => $value){
                            $_result = $this->cronjob_model->updateDL($value->phone);
                            if($_result){
                                echo 'OK '.$value->phone.'<br/>';
                            } else {
                                echo 'NO '.$value->phone.'<br/>';
                            }
            }


        }
        //function check xem booking hold nao ko nam trong muc giao ve se ra 1 list duoi day
        public function cronTicket(){
            $this->load->model('ticket_model');
            $booking = $this->cronjob_model->selectBookingTicket(2);
            foreach($booking as $key => $vals){
                $ticket = $this->ticket_model->find_by(array('booking_id'=>$vals->id));
                if($ticket){
                    
                } else {
                    echo 'Booking id = '.$vals->id.' code = '.$vals->booking_place_code.' <br/>';
                }
            }
        }
        
        public function cronBank(){
            $this->load->model('bank_model');
            $booking = $this->cronjob_model->selectBookingTicket(3);
            foreach($booking as $key => $vals){
                $ticket = $this->bank_model->find_by(array('booking_id'=>$vals->id));
                if($ticket){
                    
                } else {
                    echo 'Booking id = '.$vals->id.' code = '.$vals->booking_place_code.' <br/>';
                }
            }
        }
        
        public function cronDebts(){
            $this->load->model('debts_model');
            $booking = $this->cronjob_model->selectBookingTicket(4);
            foreach($booking as $key => $vals){
                $ticket = $this->debts_model->find_by(array('booking_id'=>$vals->id));
                if($ticket){
                    
                } else {
                    echo 'Booking id = '.$vals->id.' code = '.$vals->booking_place_code.' <br/>';
                }
            }
        }
        
        public function cronOffice(){
            $this->load->model('office_model');
            $booking = $this->cronjob_model->selectBookingTicket(5);
            foreach($booking as $key => $vals){
                $ticket = $this->office_model->find_by(array('booking_id'=>$vals->id));
                if($ticket){
                    
                } else {
                    echo 'Booking id = '.$vals->id.' code = '.$vals->booking_place_code.' <br/>';
                }
            }
        }
        
        public function checkVoiceIp() {
                $phone  = "0932055047";
//                $phone = $param->phone;

                $xml = simplexml_load_file(VOICE_IP_API.$phone);
                $arr = $this->toArray($xml->user);
                //test $arr empty ??
                $this->view_data['voiceIp']                 = new stdClass();
                $this->view_data['voiceIp']->SoGoi          = ($arr['SoGoi'])?$arr['SoGoi']:'';
                $this->view_data['voiceIp']->SoNhan          = ($arr['SoNhan'])?$arr['SoNhan']:$phone;
                $this->view_data['voiceIp']->Trangthai          = ($arr['Trangthai'])?$arr['Trangthai']:'';
                $this->view_data['voiceIp']->Thoigiangoi          = ($arr['Thoigiangoi'])?$arr['Thoigiangoi']:'';
                $this->view_data['voiceIp']->ThoigianTinhCuoc           = ($arr['ThoigianTinhCuoc'])?$arr['ThoigianTinhCuoc']:'';
                $this->view_data['voiceIp']->owner                      = $this->session->userdata['user_id'];
                $this->view_data['voiceIp']->lastupdated                = date("Y-m-d H:i:s");

                $this->load->model('voicelog_model');
                $query = $this->voicelog_model->create($this->view_data['voiceIp']);

                if($arr){
                    return $this->view_data['voiceIp'];
                } else {
                    if($function=="update"){
                        $this->session->set_flashdata('flash_message', 'H? th?ng ph?hi?n b?n chua g?i SDT '.$phone.' m??uu th??tin! H? th?ng d?og l?i h? d?ng c?a b?n');
                        redirect(site_url('auth/sales'));
                    }
                }
        }
        
         function toArray(SimpleXMLElement $xml) {
            $array = (array)$xml;

            foreach ( array_slice($array, 0) as $key => $value ) {
                if ( $value instanceof SimpleXMLElement ) {
                    $array[$key] = empty($value) ? NULL : toArray($value);
                }
            }
            return $array;
        }
        
        public function cronHistoryLog(){
            $booking = $this->cronjob_model->cronHistoryLog(30,30);
            foreach($booking as $key => $vals){
                $info = $this->paymentlog_model->find_by(array('booking_id'=>$vals->booking_id));
                if($info){
                    
                } else {
                    echo 'Booking id = '.$vals->id.' <br/>';
                }
            }
        }
		
}
